package com.example.job_backend.controller;

import com.example.job_backend.model.Query.UserQuery;
import com.example.job_backend.model.R;
import com.example.job_backend.model.User;
import com.example.job_backend.service.UserService;
import com.example.job_backend.util.AliOSSUtils;
import com.example.job_backend.util.PasswordUtils;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;


@RestController
@RequestMapping("/api")
public class UserController {
    @Resource
    private UserService userService;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @GetMapping("/user")
    public User findByUsername(String username) {
        User user = userService.findByUsername(username);
        return user;
    }

    @GetMapping("/getAllStudents")
    public R getAllStudents(){
        List<User> list=userService.getAllStudents();
        return new R(200,"请求成功",list);
    }

    @GetMapping("/users")
    public R findAllUser(UserQuery query) {
        PageInfo<User> list = userService.getUserByPage(query);
        return new R(200, "请求成功", list);
    }

    @GetMapping("/deleteUser/{id}")
    public R deleteUser(@PathVariable("id") Integer id) {
        userService.removeById(id);
        return new R(200, "请求成功", null);
    }

    @GetMapping("/addUser")
    public R addUser(User user) {
//        String salt = PasswordUtils.generateSalt();
//        System.out.println("====================");
//        System.out.println(salt);
        String passwordHash = PasswordUtils.md5WithSalt(user.getPassword(), "04943c669d0e4ca2830e402ceaa6242d");
        user.setUsername(user.getUsername());
        user.setPassword(passwordHash);
        userService.save(user);
        return new R(200, "添加成功", null);
    }

    @GetMapping("/updateUser")
    public R updateUser(User user) {
        String passwordHash = PasswordUtils.md5WithSalt(user.getPassword(), "04943c669d0e4ca2830e402ceaa6242d");
        user.setPassword(passwordHash);
        userService.updateById(user);
        return new R(200, "修改成功", null);
    }

    @GetMapping("/changepassword")
    public R changePassword(String username, String oldPassword, String newPassword) {
        userService.changePassword(username, oldPassword, newPassword);
        return new R(200, "修改成功", null);
    }

    @PostMapping("/uploadAvatar")
    public R uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException {
        String url = aliOSSUtils.uploadFile(file);
        return new R(200, "上传成功", url);
    }
}
